<template>
  <div class="data-content">
    <div class="head-content">
      <div class="head-content_btn">
        <el-button class="btnDefault" type="info" @click="addUser">添加用户</el-button>
        <!-- <el-button class="btnDefault " type="info"  @click="editUser">编辑用户</el-button> -->
      </div>
      <div class="head-content_now">
        <span>当前位置 :</span>
        <span>用户注册</span>
      </div>
    </div>
    <div class="fixThTable">
      <div class="tableBody table">
        <el-table
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
          height="660"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column prop="number" label="序号" width="180"></el-table-column>
          <el-table-column prop="rfdwmc" label="人防单位名称" width="220">
            <template slot="header">
              <div class="titleDiv">人防单位名称</div>
               <el-cascader
            :options="data"
            :props="{ checkStrictly: true }"
            style="width:80px;"
            class="noBg"
            v-model="value"
            @change="elChange"
            clearable
          ></el-cascader>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="用户账号"></el-table-column>
          <el-table-column prop="usercname" label="用户名称"></el-table-column>
          <el-table-column prop="userMd" label="用户密级"></el-table-column>
          <el-table-column prop="time" label="建立时间"></el-table-column>
          <el-table-column prop="tel" label="手机号"></el-table-column>
          <el-table-column prop="email" label="email"></el-table-column>
          <el-table-column prop="open" label="是否启用"></el-table-column>
          <el-table-column prop label="操作" width="180">
            <template slot-scope="scope">
              <span
                @click.prevent="editUser(scope.$index,scope.row)"
                class="normalColor mr10 cursor"
              >编辑用户</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="page">
        <pages :page="page" @changePage="changePage"></pages>
      </div>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form ref="formAdd" :model="form" label-width="120px" class="noBg userForm" :rules="rulesAdd">
        <el-form-item label="人防单位：" v-if="!flag">
          <!-- <el-select
            v-model="form.userMd"
            style="width:100%;"
            class="noBg border1"
            placeholder="请选择"
          >
            <el-option
              v-for="item in data"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>-->
          <el-cascader
            :options="data"
            :props="{ checkStrictly: true }"
            style="width:100%;"
            class="noBg border1"
            v-model="value"
            @change="elChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="用户账号：" prop="username">
          <el-input v-show="!flag" v-model="form.username" placeholder="请输入用户账号" class="border1"></el-input>
          <span v-if="flag">{{formList.username}}</span>
        </el-form-item>
        <el-form-item label="人防单位：" v-if="flag">
          <span>{{formList.rfdwmc}}</span>
        </el-form-item>
        <el-form-item label="用户密码：" prop="password">
          <el-input v-model="form.password" placeholder="请输入用户密码" class="border1"></el-input>
        </el-form-item>
        <el-form-item label="中文名称：" prop="usercname">
          <el-input v-model="form.usercname" placeholder="请输入中文名称" class="border1" :rules="rulesAdd"></el-input>
        </el-form-item>
        <el-form-item label="手机号码：" prop="telePhone">
          <el-input v-model="form.telePhone" placeholder="请输入手机号码" class="border1" :rules="rulesAdd"></el-input>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱号码" class="border1" :rules="rulesAdd"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button class="btnDialog" type="primary" @click="sureSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pages from "../base/pages.vue";
import moment from "moment";
import {baseServe} from "../../request/api";

export default {
  name: "yhzc",
  props: {
    msg: String
  },
  data() {
    var checkMoblie = (rule,value,callback) => {
      if(!value.trim()){
          return callback(new Error('请输入手机号'))
      }
      if(!/^1[34578]\d{9}$/.test(value)){
        return callback(new Error('手机号有误！请重填！'))
      }else{
        callback()
      }
    }
    return {
      dialogTitle:'',
      ID: "",
      num: 0,
      flag: false,
      formList: {
        rfdwmc: "",
        username: ""
      },
      value: "",
      userMd: "",
      page: {
        //总条数
        total: 0,
        //每页条数
        limit: 10,
        //当前页数
        currentPage: 1,
        pageSizes: [10,25],
        //实际返回的条数
        dataLength: 7
      },
      data: [],
      options: [
        {
          value: "10",
          label: "非密"
        },
        {
          value: "20",
          label: "内部"
        },
        {
          value: "30",
          label: "秘密"
        },
        {
          value: "40",
          label: "机密"
        }
      ],
      tableData: [
      ],
      dialogVisible: false,
      form: {
        rfdwnm: "",
        username: "",
        password: "",
        usercname: "",
        telePhone: "",
        email: "",
        userMd: ""
      },
      rulesAdd:{
        username:[
          {required:true,message:'请输入用户账号',trigger:'blur'},
          {min:6,max:10,message:'长度6到10个字符',trigger:'blur'}
        ],
        password:[
          {required:true,message:'请输入用户密码',trigger:'blur'},
          {min:4,max:10,message:'长度4到10个字符',trigger:'blur'}
        ],
        usercname:[
          {required:true,message:'请输入用户中文名称',trigger:'blur'},
          {min:2,max:10,message:'长度2到10个字符'},
          {pattern:/^[\u4E00-\u9FA5]+$/,message:'用户名只能为中文'}
        ],
        telePhone:[
          {required:true,message:'请输入手机号',trigger:'blur'},
          {validator:checkMoblie,trigger:'blur'}
        ],
        email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
          {pattern:/^[a-zA-z0-9]+@[a-zA-z0-9]+\.\w{2,3}$/,message:'请输入正确的邮箱地址'}
        ]
    },
    };
  },
  mounted() {
    this.formLisr();
    this.treeList();
  },
  computed: {
    TreeRfdwnm() {
      return this.$store.state.TreeRfdwnm;
      // return localStorage.getItem("TreeRfdwnm")
    }
  },
  watch: {
    TreeRfdwnm() {
      this.page.limit = 10;
      this.page.currentPage = 1;
      this.formLisr();
    }
  },
  methods: {
    elChange() {
      this.$store.state.TreeRfdwnm=this.value[this.value.length-1]
      localStorage.setItem("TreeRfdwnm",this.value[this.value.length-1])
      // this.treeList()
    },
    //单位选择
    treeList() {
      this.data = [];
      let params = {
        rfdwnm: 821
      };
      baseServe.cityList(  params ).then(res => {
        res = res.data.qgrfdwModels;
        res.forEach(item => {
          this.data.push({
            label: item.rfdwmc,
            value: item.xh,
            children: item.qgrfdwModels.map(i => {
              let obj = {
                label: i.rfdwmc,
                value: i.xh,
                children: i.qgrfdwModels.map(j => {
                  let obj = {
                    label: j.rfdwmc,
                    value: j.xh
                  };
                  return obj;
                })
              };
              return obj;
            })
          });
        });
      });
    },
    //保存按钮
    iconSave(){},
    //列表数据
    formLisr() {
      let params = {
        limit: this.page.limit,
        start: this.page.currentPage,
        rfdwnm: localStorage.getItem("TreeRfdwnm")
          ? localStorage.getItem("TreeRfdwnm")
          : 821
      };

      this.$axios.get("/rfdwnm/query", { params }).then(res => {
        this.tableData = [];

        this.page.total = res.data.totoalCount;
        res = res.data.users;
        res.forEach((item, index) => {
          this.userMd = "";
          switch (item.secrectLevel) {
            case "10":
              this.userMd = "非密";
              break;
            case "20":
              this.userMd = "内部";
              break;
            case "30":
              this.userMd = "秘密";
              break;
            case "40":
              this.userMd = "机密";
              break;
          }
          this.tableData.push({
            rfdwnm: item.rfdwnm,
            userID: item.userID,
            number: index + 1,
            rfdwmc: item.rfdwmc,
            username: item.account,
            usercname: item.userName,
            time: moment(item.createTime).format("YYYY-MM-DD HH:mm:ss"),
            userMd: this.userMd,
            tel: item.mobile,
            email: item.email,
            psw: item.password,
            open: item.status == 0 ? "否" : "是 "
          });
        });
      });
    },
    sureSave() {
      if (this.num !== 0) {
        let params = {
          rfdwnm: this.form.rfdwnm,
          userID: this.ID,
          account: this.formList.username,
          userName: this.form.usercname,
          password: this.form.password,
          mobile: this.form.telePhone,
          email: this.form.email,
          secrectLevel: this.form.userMd,
          serviceName: localStorage.getItem("serverName")
        };
        if (
          this.form.rfdwnm &&
          this.form.usercname &&
          this.form.telePhone &&
          this.form.email &&
          this.form.userMd !== ""
        ) {
          this.$refs.formAdd.validate(async valid=>{
            if(!valid) {
              this.$message({
                    type: 'info',
                    message: '请修改错误信息'
                });
                return null
            }

            this.$axios.post("/update", params).then(res => {
            if ((res.data.result.resultCode == "000000")) {
              this.addFlag = false;
              this.$message({
                type: "success",
                message: "编辑成功!"
              });
              this.dialogVisible = false;
              this.formLisr();
              //this.form = ""
            }
          });
          })

        } else {
          this.$message({
            type: "error",
            message: "请确认填写信息是否完整!"
          });
        }
      } else {
        let params = {
          rfdwnm: this.value[this.value.length-1],
          account: this.form.username,
          userName: this.form.usercname,
          password: this.form.password,
          mobile: this.form.telePhone,
          email: this.form.email,
          secrectLevel: this.form.userMd,
          serviceName: localStorage.getItem("serverName")
        };
        if (
          params.rfdwnm &&
          params.password &&
          params.userName &&
          params.mobile &&
          params.email
        ) {
          this.$refs.formAdd.validate(async valid=>{
            if(!valid) {
              this.$message({
                    type: 'info',
                    message: '请修改错误信息'
                });
                return null
            }
            this.$axios.post("/create", params).then(res => {
            if ((res.data.result.resultCode == "000000")) {
              this.addFlag = false;
              this.$message({
                type: "success",
                message: "新增成功!"
              });
              this.dialogVisible = false;
              this.formLisr();
              // this.form = {}
              // this.value = ""
            }else if((res.data.result.resultCode == "99009")) {
              this.$message({
                type: "warning",
                message: "用户账号已存在，请重新输入!"
              });
            }
          });
        })
        } else {
          this.$message({
            type: "error",
            message: "请确认填写信息是否完整!"
          });
        }
      }
    },

    addUser() {
      this.dialogTitle = '添加用户';
      this.num = 0;
      this.flag = false;
      this.dialogVisible = true;
      this.value = ""
      this.form = {
        rfdwnm: "",
        username: "",
        password: "",
        usercname: "",
        telePhone: "",
        email: "",
        userMd: ""
      },
      this.$refs.formAdd.resetFields()
    },
    editUser(index, row) {
      this.dialogTitle = '编辑用户';
      this.num = row.number;
      this.ID = row.userID;
      this.formList.rfdwmc = row.rfdwmc;
      this.formList.username = row.username;
      this.form.rfdwnm = row.rfdwnm;
      this.form.username = row.username;
      this.form.password = row.psw;
      this.form.usercname = row.usercname;
      this.form.telePhone = row.tel;
      this.form.email = row.email;
      this.form.userMd = row.secrectLevel;
      this.flag = true;
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    linkTo(id) {},
    changePage(data) {
      this.formLisr();
      this.page = data;
    }
  },
  components: {
    pages
  }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less">
.data-content {
  width: 100%;
  height: 100%;
  // overflow: auto;
  position: relative;
  color: #ffffff;
  font-size: 14px;
  box-sizing: border-box;
  .head-content {
    display: flex;
    height: 7%;
    line-height: 2;
    justify-content: space-between;
    padding: 0 20px;
    color: #fff;
    box-sizing: border-box;
    .head-content_btn {
      width: 80%;
      margin-top: 10px;
    }
    .head-content_now {
      // width: 20%;
      margin-top: 20px;
    }
  }

  .table {
    height: 660px;
    // overflow: auto;
    // position: absolute;
    top: 35px;
    bottom: 0;
    left: 0;
    right: 0;
    margin: 20px;
  }
  // .page{
  //   // position: absolute;
  //   // margin-bottom: 0;
  // }

  .el-form-item__label {
    color: #00ffff;
  }
}
</style>
